// proxySeriveManage.js
const app = getApp()
const util = require("../../utils/util.js")

Page({
  /*页面的初始数据*/
  data: {
    type:0,
    myid:'',
    list: [],
    result: [],
    surplusRate:'',
    updateData:''
  },
  onChange(event) {
    this.setData({
      result: event.detail
    });
  },
  rateChange:function(event){
    var i = event.currentTarget.dataset.index;
    this.setData({
      ['list['+i+'].commission']:event.detail
    })
  },
  // 管理店铺
  shopList: function () {
    var that = this;
    var type = that.data.type;
    var myid = that.data.myid;
    var data = { type:type };
    app.post('agent/getAgentShopList', data).then((res) => {
      if (res.code == 200) {
        var list = res.list;
        var result = [];
        for(var i = 0;i<list.length;i++){
          if (list[i].id == myid) {
            result.push(list[i].shopId.toString())
          }
        }
        that.setData({
          list:list,
          result:result
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg)
      wx.showToast({
        title: "网络错误",
        icon: 'loading',
        duration: 2000
      })
    })
  },
  update:function(){
    var that = this;
    var result = that.data.result;
    var data = [], dataCell = '', shopID = '', rate = '';
    for(var i = 0; i<result.length;i++){
      that.data.list.filter(function(item){
        if (item.shopId == result[i]){
          shopID = item.shopId.toString();
          rate = item.commission?item.commission.toString() : 0;
          dataCell = shopID + '-' + rate
        }
      })
      data.push(dataCell)
    }
    that.setData({
      updateData:data
    })
    that.updateAPI()
    
  },
  updateAPI:function(){
    var that = this;
    var result = that.data.updateData;
    var shop = result.join("#");
    var data = {
      id: that.data.myid,
      type: that.data.type,
      shop: shop
    };
    wx.showLoading({
      title: '加载中...',
    })
    app.post('agent/updateEmployee', data).then((res) => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: res.message,
          icon: 'success',
          duration: 2000
        })
        wx.navigateBack({
          delta: 1
        })
      } else {
        wx.showToast({
          title: "提交失败",
          icon: 'loading',
          duration: 2000
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);
      wx.hideLoading();
      wx.showToast({
        title: "网络错误",
        icon: 'loading',
        duration: 2000
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      type: options.active == 0 ? 'engineer':'saleman',
      myid: options.myid,
      surplusRate: app.globalData.agentRate
    })
    this.shopList();
  }
})